<template>
  <div class="rate-editor">
    <h3>评分题</h3>
    <el-form :model="localModel" label-position="left" label-width="100px" ref="rateForm">
      <el-form-item label="标题" prop="title" required>
        <el-input v-model="localModel.title"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="localModel.description"></el-input>
      </el-form-item>
      <el-form-item label="最大分值" prop="max" required>
        <el-input v-model.number="localModel.max"></el-input>
      </el-form-item>
      <el-form-item label="必做" prop="must">
        <el-switch v-model="localModel.must"></el-switch>
      </el-form-item>
    </el-form>
    <div class="q-item q-item-control">
      <el-button type="primary" @click="handleSave">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "Qeditorrate",
  props: {
    options: {
      type: Object,
      default: function() {
        return {
          autoJudge: false,
          showResult: false,
          limitNumber: false
        };
      }
    },
    setting: {
      type: Object,
      default: function() {
        return {
          type: "rate",
          must: true,
          title: "评分题",
          description: "我是评分题",
          max: 5,
          min: 0
        };
      }
    }
  },
  data() {
    return {
      localModel: {}
    };
  },
  methods: {
    loadOrigin() {
      // 保存一份副本，以便取消更改时复原
      this.localModel = JSON.parse(JSON.stringify(this.setting));
    },
    handleSave() {
      // 否则检测是否满足验证函数
      // 满足则将新的表单提交给上级
      this.$refs.rateForm.validate(valid => {
        if (valid) {
          this.$emit("change", this.localModel);
        } else {
          this.$message({ type: "warning", message: "请检查信息是否完整" });
        }
      });
    },
    handleCancel() {
      // 取消则还原修改
      this.loadOrigin();
      this.$emit("cancel", this.localModel);
    },
    removeOption(index) {
      if (this.localModel.options.length > 1)
        this.localModel.options.splice(index, 1);
      else {
        this.$message("至少保留一个选项");
      }
    },
    addOption() {
      this.localModel.options.push({ value: "新选项" });
    }
  },
  mounted() {
    console.log('rate'+this.localModel)
    this.loadOrigin();
  },
  watch: {
    setting(newVal, oldVal) {
      this.loadOrigin();
    }
  }
};
</script>

<style scoped>
.rate-editor .add_option {
  display: inline-block;
  zoom: 1;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  border: 1px dashed #e0e0e0;
  padding: 6px 10px;
  background: #fafafa;
  color: #b2b2b2;
  cursor: pointer;
  font-size: 14px;
  line-height: 1.8em;
}
.rate-editor .option {
  display: flex;
  margin: 10px;
}
.rate-editor .option .el-input {
  width: 75%;
  margin: 0 50px 0 0;
}
</style>